package me.humin.nio.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author humin
 * @create 2018-7-4
 */
public class NioClient {

    private Selector selector;

    private SocketChannel channel;

    private boolean watching = false;

    public void connectServer(String ip, int port) throws Exception {
        if (channel != null && channel.isConnected()) {
            throw new Exception("already connected");
        }
        if (channel == null) {
            channel = SocketChannel.open();
            channel.configureBlocking(false);
        }
        if (selector == null) {
            selector = Selector.open();
        }
        if (!channel.isRegistered()) {
            channel.register(selector, SelectionKey.OP_CONNECT);
        }
        channel.connect(new InetSocketAddress(ip, port));
        while (!channel.finishConnect()) {}
        channel.register(selector, SelectionKey.OP_WRITE|SelectionKey.OP_READ);
    }

    private void watchSelector() {
        if (watching) {
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                watching = true;
                try {
                    while (true) {
                        selector.selectNow();
                        Set<SelectionKey> set = selector.selectedKeys();
                        Iterator<SelectionKey> iterator = set.iterator();
                        while (iterator.hasNext()) {
                            SelectionKey selectionKey = iterator.next();
                            if (selectionKey.isConnectable()) {
                                SocketChannel channel = (SocketChannel) selectionKey.channel();
                                while (!channel.finishConnect()) {}
                                channel.register(selector, SelectionKey.OP_WRITE|SelectionKey.OP_READ);
                            }
                            if (selectionKey.isWritable()) {

                            }
                            iterator.remove();
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    watching = false;
                }
            }
        }).start();
    }

    public static void main(String[] args) throws IOException {
    }

}
